package com.ciwong.epaper.modules.epaper.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.TrafficStats;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.common.CheckIsExamForDetail;
import com.ciwong.epaper.modules.dbbean.LswAnswer;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.ListenspeakExam;
import com.ciwong.epaper.modules.epaper.bean.LswScoreResult;
import com.ciwong.epaper.modules.epaper.bean.LswUploadResult;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.bean.Questions;
import com.ciwong.epaper.modules.epaper.bean.RecordSubmitPart;
import com.ciwong.epaper.modules.epaper.bean.ResourceDetail;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.dao.LswDao;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.me.bean.MyWork;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.AddPointTypes;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.modules.share.QQShareHelper;
import com.ciwong.epaper.modules.share.QQShareListener;
import com.ciwong.epaper.modules.share.WxShareHelper;
import com.ciwong.epaper.modules.share.WxShareListener;
import com.ciwong.epaper.modules.share.bean.ShareMsgObj;
import com.ciwong.epaper.util.Base64Utils;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.widget.NetWorkTipsDialog;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.epaper.widget.SubmitSuccessfulResultPage;
import com.ciwong.epaper.widget.TopWarningMsgDialog;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.BuyServiceDialog;
import com.ciwong.mobilelib.widget.CWDialog;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.UiError;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 听说模考结果界面 Created by pla-gysu on 2015/8/7.
 */
public class ListenSpeakResultActivity extends BaseActivity implements View.OnClickListener {

    public static final String TAG = "retryscore2";
    private final int MSG_NET_SPEED = 100;
    private final int MSG_NET_TIPS = 103;
    private final int MSG_WEAK_NET_TIPS_SHOW = 105;
    private final int MSG_WEAK_NET_TIPS_HIDE = 107;
    private final int RESULT_STATE_UPLOADING = 0;
    private final int RESULT_STATE_UPLOAD_SUCCESS = 1;
    private final int RESULT_STATE_EVALUATE_SUCCESS = 2;
    private final int RESULT_STATE_UPLOAD_FAIL = -1;
    private DownLoadInfo mDownLoadInfo;
    private Module mModule;
    private int position;
    private String mWorkId = "0";
    private String mClassId;
    protected int mServiceId;
    private ImageView img_upload_state;
    private SubmitSuccessfulResultPage score_result_page;
    private View result_lay;//结果
    private View handle_state_upload_ing;
    private SeekBar seek_bar_make_score;
    private Button btn_retry_commit;
    private TextView tx_upload_progress;
    private TextView tx_low_net_speed_tips;
    private int totalTime;
    private boolean isSubmited = false;// 是否已提交过作业
    private static final int REQ_CODE_TO_JOIN_CLASS = 1;// 去加入班级requestCode
    private long returnWorkLong;
    private EApplication application;
    /**
     * 默认服务包剩余使用时间
     */
    public boolean serviceExpired;
    //本地作业列表
    private List<MyWork> mLocalWorkList;

    //截止时间
    private long effectiveDate = -1;

    // 查看类型：0 提交立马能查看，1截止时间到后查看
    private int showScoreMod;

    private long nowDate;

    //用于防止多次提交
    //    private boolean submitCallback = true;

    protected ArrayList<LswAnswer> mLswAnswerList = new ArrayList<LswAnswer>();
    private int progress = 0;
    private NetWorkTipsDialog mNetWorkTipsDialog;
    private int mRetryIndex = 0;
    private Timer timer = new Timer();
    private boolean isRetryOver = true;
    private LswUploadResult mLswUploadResult;
    private int remainUploadSize;
    private boolean isShowWeekTips = false;
    protected String checkedResource;
    private LswScoreResult mLswScoreResult;
    private Context mContext;
    private String mTitleText;
    private ListenspeakExam mExamData;
    private long startTime;


    private WorkContents mWorkContents;

    protected int lsMode;

    protected int doWorkType;

    private float mTotalScore;

    private int mContentId = 0;
    private boolean ishasObj = false;

    private ImageView wechat, wechatFriend, qq, qqFriend;//分享
    private CWDialog dialogExt;
    private boolean isCorrect;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case MSG_NET_SPEED:
                    int speed = (int) msg.obj;
                    //                    Log.d(TAG, "################speedStr################"+speed);
                    if (speed < 10 && !isShowWeekTips) {
                        isShowWeekTips = true;
                        mHandler.sendEmptyMessageDelayed(MSG_WEAK_NET_TIPS_SHOW, 2000);
                    }

                    remainUploadSize = remainUploadSize - speed;

                    if (remainUploadSize < 0) {
                        remainUploadSize = 0;
                    }

                    int remainSecods = 0;
                    if (speed > 0) {
                        remainSecods = remainUploadSize / speed;
                    } else {
                        //如果网速为0 当做1kb
                        remainSecods = remainUploadSize;
                    }
                    //                    Log.d(TAG, "################remainUploadSize################"+remainUploadSize);
                    if (!isOnlyChoiceOrBlank()) {
                        tx_upload_progress.setVisibility(View.VISIBLE);
                        tx_upload_progress.setText(ListenSpeakUtil.formatNetSpeed(ListenSpeakResultActivity.this, speed, remainSecods, true));
                    } else {
                        //无法估计剩余时间
                        tx_upload_progress.setVisibility(View.GONE);
                        //                        tx_upload_progress.setText(ListenSpeakUtil.formatNetSpeed(ListenSpeakResultActivity.this,speed,remainSecods,false));
                    }
                    break;
                case MSG_NET_TIPS:

                    if (null != mNetWorkTipsDialog && mNetWorkTipsDialog.isShowing()) {
                        mNetWorkTipsDialog.dismiss();
                    }

                    break;
                case MSG_WEAK_NET_TIPS_SHOW:

                    Animation animation = AnimationUtils.loadAnimation(ListenSpeakResultActivity.this, R.anim.slide_down2);
                    tx_low_net_speed_tips.startAnimation(animation);
                    tx_low_net_speed_tips.setVisibility(View.VISIBLE);
                    mHandler.sendEmptyMessageDelayed(MSG_WEAK_NET_TIPS_HIDE, 3000);

                    break;
                case MSG_WEAK_NET_TIPS_HIDE:
                    Animation animation2 = AnimationUtils.loadAnimation(ListenSpeakResultActivity.this, R.anim.slide_up2);
                    animation2.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            tx_low_net_speed_tips.setVisibility(View.GONE);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    tx_low_net_speed_tips.startAnimation(animation2);
                    break;
            }
        }
    };


    @Override
    protected void preCreate() {
        super.preCreate();

        mDownLoadInfo = (DownLoadInfo) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
        mModule = (Module) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        position = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
        String workId = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);

        if (!TextUtils.isEmpty(workId)) {
            mWorkId = workId;
        }

        mClassId = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_CLASS_ID);
        mServiceId = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);
        totalTime = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_WORK_TIME, 1);
        checkedResource = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_CHECKED_RESOURCE);
        mLswAnswerList = (ArrayList<LswAnswer>) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ_LIST);
        mExamData = (ListenspeakExam) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_LSW_EXAM);
        mWorkContents = (WorkContents) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_LSW_WORK_CONTENTS);
        lsMode = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_ACTION, ListenSpeakUtil.LsMode.OWN_PRACTISE);
        doWorkType = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_DO_WORK_TYPE, 0);
        effectiveDate = getIntent().getLongExtra(IntentFlag.INTENT_FLAG_WORK_EFFECTIV_TIME, -1);
        isCorrect = getIntent().getBooleanExtra(IntentFlag.INTENT_FLAG_CORRECT, false);
        //是否有主观题
        ishasObj = isobj(mLswAnswerList);
        startTime = CWSys.getSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, mWorkId), 0);
        if (startTime == 0) {
            startTime = mDownLoadInfo.getStartTime();
        }

    }

    private boolean isobj(ArrayList<LswAnswer> LswAnswerList) {
        try {
            for (LswAnswer l : LswAnswerList
            ) {
                if (l.getIs_objective() == 0) {
                    return true;
                }

            }

        } catch (Exception e) {
            e.getStackTrace();
        }

        return false;
    }


    @Override
    protected void init() {
        setValideSource(false);
        application = (EApplication) getApplication();
        if (application != null) {
            //服务是否过期
            serviceExpired = application.isServiceExpired();
        }
        if (!serviceExpired) {
            if (mWorkContents != null && mWorkContents.getIsFree() == 1) {
                serviceExpired = true;
            }
        }
        mContext = this;
        getExamData();
        if (lsMode == ListenSpeakUtil.LsMode.OWN_PRACTISE && null != mExamData) {
            mTotalScore = mExamData.getTotalScore();

            score_result_page.setToalScore(mExamData.getTotalScore());

        } else if (lsMode == ListenSpeakUtil.LsMode.HOME_WORK_MODE && mWorkContents != null) {

            mTotalScore = mWorkContents.getWorkScore();
            if (doWorkType == 1) {
                mTotalScore = mWorkContents.getErrorWorkScore();
            }
            if (mWorkContents.getContentId() > 0)
                mContentId = mWorkContents.getContentId();
            score_result_page.setToalScore(mWorkContents.getWorkScore());
        }
        //        setTitleText(mModule.getResourceList().get(position).getResourceName());

        hideTitleBar();
        setBackImg(R.mipmap.icon_x_exit);
        updateStateImg(RESULT_STATE_UPLOADING, 0);
        String uuid = CWSys.getSharedString(ListenSpeakUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, mWorkId, doWorkType), null);

        if (null == uuid) {
            if (isCorrect) {
                uuid = "isCorrect";
            } else {
                //有可能提交成功清除uuid后再结果页面停留或者用清理软件销毁当前页面，重新生成页面后 uuid 没有
                finish();
            }
        }
        CWSys.setSharedBoolean(ListenSpeakUtil.getBeenToLswResultRecord(mDownLoadInfo, mModule, position, mWorkId, uuid), true);

        if (!EConstants.IS_YOUKE) {
            if (mLswAnswerList != null) {
                if (isHashUploadFail()) {
                    startRetry();
                } else {
                    commitHomeWork();
                }
            }
            new Timer().schedule(netSpeedTask, 1000, 1000); // 1s后启动任务，每2s执行一次
        }
    }

    @Override
    protected int setView() {
        return R.layout.listen_speak_result;
    }

    @Override
    protected void onResume() {
        super.onResume();
        WxShareHelper.getInstance().onResumeResultData();

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.btn_retry_commit == id) {
            if (EConstants.IS_YOUKE) {
                NewLoginDialog newLoginDialog = new NewLoginDialog(ListenSpeakResultActivity.this);
                newLoginDialog.showLoginDialog();
            } else {
                startRetry();
            }


        } else if (R.id.img_arrow_shuaxin == id) {

            if (NetworkUtils.isOnline()) {
                if (null != mLswUploadResult) {
                    getScoreResult(mLswUploadResult.getDoworkId());
                }
            } else {
                mNetWorkTipsDialog = new NetWorkTipsDialog(this, getString(R.string.connect_disable5));
                mNetWorkTipsDialog.show();
                mHandler.sendEmptyMessageDelayed(MSG_NET_TIPS, 2000);
            }


        }

    }


    private void startRetry() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateStateImg(RESULT_STATE_UPLOADING, 0);
            }
        });

        if (NetworkUtils.isOnline()) {
            if (mLswAnswerList != null && mLswAnswerList.size() > 0) {

                mRetryIndex = 0;
                for (int i = mRetryIndex; i <= mLswAnswerList.size(); i++) {
                    mRetryIndex = i;
                    if (i < mLswAnswerList.size() && mLswAnswerList.get(i).getUploadState() == LswAnswer.FAIL
                            && (mLswAnswerList.get(i).getAnswerType() != Questions.AnswerType.QUESTION_TYPE_CHOICE)
                            && (mLswAnswerList.get(i).getAnswerType() != Questions.AnswerType.QUESTION_TYPE_FILL_BLANK)) {
                        break;
                    }
                }
                progress = 0;
                seek_bar_make_score.setProgress(progress);
                seek_bar_make_score.setMax(mLswAnswerList.size());
                isRetryOver = false;
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {

                        progress = getSuccessCount();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                seek_bar_make_score.setProgress(progress);
                                //                                String uploadCountProgress = "(" + progress + "/" + mLswAnswerList.size() + ")";
                                //                                tx_upload_progress.setText(uploadCountProgress);
                            }
                        });

                        if (isRetryOver) {// 上传结束
                            cancel();
                        }

                    }
                }, 0, 1000);
            }

            if (mRetryIndex < mLswAnswerList.size()) {

                isShowWeekTips = false;

                remainUploadSize = (int) getRemainUploadFileSize();

                onUploadStateDeal();

            } else if (mRetryIndex == mLswAnswerList.size()) {
                if (EConstants.IS_YOUKE) {
                    NewLoginDialog newLoginDialog = new NewLoginDialog(ListenSpeakResultActivity.this);
                    newLoginDialog.showLoginDialog();
                } else {
                    commitHomeWork();
                }

            }

        } else {
            updateStateImg(RESULT_STATE_UPLOAD_FAIL, 0);
            //            mNetWorkTipsDialog = new NetWorkTipsDialog(this, getString(R.string.connect_disable5));
            //            mNetWorkTipsDialog.show();
            mHandler.sendEmptyMessageDelayed(MSG_NET_TIPS, 2000);
        }

    }


    @Override
    public void onBackPressed() {
        goBackListener.goBack();
    }

    /**
     * 退出提示框
     */
    private void showConfirmEndDialog() {
        if (isDestroy) {
            return;
        }
        CWDialog dialog = new CWDialog(this);
        dialog.setMessage(R.string.confirm_no_submit_work);
        dialog.setCancelable(true);
        dialog.setPositiveButton(android.R.string.cancel, null)
                .setNegativeButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();

                                finish();

                            }
                        })
                .show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_QQ_SHARE || requestCode == Constants.REQUEST_QZONE_SHARE) {
            QQShareHelper.getInstance().onActivityResultData(requestCode, resultCode, data);

        } else if (resultCode == RESULT_OK) {

            if (requestCode == REQ_CODE_TO_JOIN_CLASS) {// 加入班级成功
                if (EConstants.IS_YOUKE) {
                    NewLoginDialog newLoginDialog = new NewLoginDialog(ListenSpeakResultActivity.this);
                    newLoginDialog.showLoginDialog();
                } else {
                    startRetry();
                }

                //                submitAnswer();
            } else if (requestCode == EpaperConstant.REQUEST_CODE_TO_RANK_PAGE || requestCode == EpaperConstant.REQUEST_CODE_TO_H5_RECORD_PAGE) {
                if (null != mLswUploadResult) {
                    getScoreResult(mLswUploadResult.getDoworkId());
                }
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WxShareHelper.getInstance().release();
        QQShareHelper.getInstance().release();
    }

    @Override
    protected void findViews() {
        img_upload_state = (ImageView) findViewById(R.id.img_upload_state);
        handle_state_upload_ing = findViewById(R.id.handle_state_upload_ing);
        seek_bar_make_score = (SeekBar) findViewById(R.id.seek_bar_make_score);
        btn_retry_commit = (Button) findViewById(R.id.btn_retry_commit);
        tx_upload_progress = (TextView) findViewById(R.id.tx_upload_progress);
        tx_low_net_speed_tips = (TextView) findViewById(R.id.tx_low_net_speed_tips);
        score_result_page = findViewById(R.id.score_result_page);
        result_lay = findViewById(R.id.result_lay);

        wechat = (ImageView) score_result_page.findViewById(R.id.share_weixin);
        wechatFriend = (ImageView) score_result_page.findViewById(R.id.share_weixin_friend);
        qq = (ImageView) score_result_page.findViewById(R.id.share_qq);
        qqFriend = (ImageView) score_result_page.findViewById(R.id.share_qq_space);
        isSupportQQAndQQZone();

    }

    @Override
    protected void initEvent() {

        btn_retry_commit.setOnClickListener(this);
        score_result_page.setOnRefreshScoreListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (NetworkUtils.isOnline()) {
                    if (null != mLswUploadResult) {
                        getScoreResult(mLswUploadResult.getDoworkId());
                    }

                } else {
                    mNetWorkTipsDialog = new NetWorkTipsDialog(ListenSpeakResultActivity.this, getString(R.string.connect_disable5));
                    mNetWorkTipsDialog.show();
                    mHandler.sendEmptyMessageDelayed(MSG_NET_TIPS, 2000);
                }

            }
        });

        score_result_page.setOnCheckDetailListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(ListenSpeakResultActivity.this, mContentId + "", 0);
                if (!orNotWatchDetails)
                    return;
                if (serviceExpired) {
                    // 直接跳转到新的学习记录页面
                    jumpToStudyRecordH5();
                } else {
                    setBuyServiceDialog();
                }
            }
        });
        score_result_page.setOnCheckTipsListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(ListenSpeakResultActivity.this, mContentId + "", 0);
                if (!orNotWatchDetails)
                    return;
                if (serviceExpired) {
                    // 直接跳转到新的学习记录页面
                    jumpToStudyRecordH5();
                } else {
                    setBuyServiceDialog();
                }
            }
        });

        wechat.setOnClickListener(new ViewOnClickListener() {//微信分享
            @Override
            public void avertRepeatOnClick(View v) {
                weChatShare(1);//微信朋友分享
            }
        });
        wechatFriend.setOnClickListener(new ViewOnClickListener() {//
            @Override
            public void avertRepeatOnClick(View v) {
                weChatShare(2);//微信朋友圈
            }
        });

        qq.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                qqShare("QQ");
            }
        });

        qqFriend.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                qqShare("QZone");
            }
        });
        setGoBackListener(goBackListener);

    }

    /**
     * 直接跳转到新的学习记录页面
     */
    private void jumpToStudyRecordH5() {
        //直接跳转到新的学习记录页面
        if (null != mLswScoreResult) {
            //为了与查看详情取资源匹配，同步其他地方，默认只有一个module Content
            try {
                //直接跳转到新的学习记录页面
                String url = EpaperConstant.URL_LSW_DETAILS;
                StringBuffer sb = new StringBuffer(url);
                sb.append("&clientId=");
                sb.append(EConstants.CLIENT_ID);
                long useeId = getUserInfoBase().getUserId();
                sb.append("&userId=");
                sb.append(useeId);
                sb.append("&brandId=");
                sb.append(EApplication.BRAND_ID);
                sb.append("&versionId=");
                sb.append(mExamData.getVersionId());
                sb.append("&doWorkId=");
                if (null != mLswUploadResult) {
                    sb.append(mLswUploadResult.getDoworkId());
                } else {
                    sb.append(mWorkContents.getDoWorkId());
                }
                sb.append("&revisedMode=1");
                String title;
                try {
                    title = java.net.URLEncoder.encode(mTitleText, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    title = "";
                }
                title = title.replace("+", "%20");
                sb.append("&title=");
                sb.append(title);
                sb.append("&doWorkType=");
                sb.append(doWorkType);
                sb.append("&disableChoiceAndFillRevised=1");
                MeJumpManager.jumpToStudyRecordH5Activity(ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT, ListenSpeakResultActivity.this, R.string.go_back, EpaperConstant.REQUEST_CODE_TO_H5_RECORD_PAGE, sb.toString(), mTitleText, doWorkType);
                finish();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private BuyServiceDialog buyServiceDialog;

    public void setBuyServiceDialog() {
        if (buyServiceDialog == null) {
            buyServiceDialog = new BuyServiceDialog(ListenSpeakResultActivity.this);
            buyServiceDialog.setMenuOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    //购买服务包
                    MeJumpManager.jumpBuyService(ListenSpeakResultActivity.this, R.string.go_back, mServiceId, -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, "");
                    buyServiceDialog.dismiss();
                }
            });
            buyServiceDialog.setClosOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    buyServiceDialog.dismiss();
                }
            });
        }
        buyServiceDialog.show();
    }

    /**
     * "QQ"代表分享给QQ好友，"QZone"代表分享到QQ空间
     *
     * @param qq
     */

    private void qqShare(String qq) {
        ShareMsgObj shareMsgObj = new ShareMsgObj();
        shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);
        shareMsgObj.setLocalImgUrl(FileUtil.getShareIconLocalPath(getApplicationContext()));
        String sharePara = null;
        if (null != mLswUploadResult && mExamData != null) {
            sharePara = getString(R.string.str_share_para, EConstants.CLIENT_ID, String.valueOf(getUserInfoBase().getUserId()), String.valueOf(EApplication.BRAND_ID), mExamData.getVersionId(), mLswUploadResult.getDoworkId());
            Log.d(TAG, "########shareUrl#########" + sharePara);
            String strBase64 = Base64Utils.getBase64(sharePara);
            String shareUrl = EpaperConstant.URL_LSW_SHARE + strBase64;
            shareMsgObj.setUrl(shareUrl);
            String shareContent;
            if (mLswScoreResult != null && mLswScoreResult.getStatus() != EpaperConstant.SCORE_STATUS_UNCOMPLETE && mLswScoreResult.getStatus() != EpaperConstant.SCORE_STATUS_TSMK_UNCOMPLETE
                    && mLswScoreResult.getStatus() != EpaperConstant.SCORE_STATUS_ONLINEANSWER_UNCOMPLETE) {
                String score = getString(R.string.speech_word_score, MeUtil.formatScore(mLswScoreResult.getScore()));
                shareContent = getString(R.string.str_share_content, score);
            } else {
                shareContent = getString(R.string.str_share_content2);
            }
            try {

                if (qq.equals("QQ")) {
                    shareMsgObj.setMsgTitle(mTitleText);
                    shareMsgObj.setMsgDesription(shareContent);
                    if (!isFinishing()) {
                        QQShareHelper.getInstance().shareToQQ(ListenSpeakResultActivity.this, shareMsgObj, new QQShareListener() {
                            @Override
                            public void onQQShareSucc(Object var) {
                                ToastUtil.INSTANCE.toastCenterSuccess("分享成功");
                                shareAddPointType(mLswUploadResult.getDoworkId(), AddPointTypes.SHERE_SCORE);
                            }

                            @Override
                            public void onQQShareFailure(UiError var1) {
                            }

                            @Override
                            public boolean onQQShareCancel() {
                                return false;
                            }
                        });
                    }
                } else if (qq.equals("QZone")) {
                    shareMsgObj.setMsgTitle(shareContent);
                    shareMsgObj.setImg_url(FileUtil.getShareIconLocalPath(getApplicationContext()));
                    QQShareHelper.getInstance().shareToQZone(ListenSpeakResultActivity.this, shareMsgObj, new QQShareListener() {
                        @Override
                        public void onQQShareSucc(Object var) {
                            ToastUtil.INSTANCE.toastCenterSuccess("分享成功");
                            shareAddPointType(mLswUploadResult.getDoworkId(), AddPointTypes.SHERE_SCORE);
                        }

                        @Override
                        public void onQQShareFailure(UiError var1) {
                        }

                        @Override
                        public boolean onQQShareCancel() {
                            return false;
                        }
                    });
                }

            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 1代表分享给好友，2代表分享到朋友圈
     *
     * @param wxType
     */
    private void weChatShare(int wxType) {
        WxShareHelper.getInstance().initWxShare(ListenSpeakResultActivity.this, new WxShareListener() {
            @Override
            public void onWxShareing(String str) {
                ToastUtil.INSTANCE.toastInCenter(mContext, "分享中...");
            }

            @Override
            public void onWxShareSucc(String var) {
                ToastUtil.INSTANCE.toastCenterSuccess("分享成功");
                shareAddPointType(mLswUploadResult.getDoworkId(), AddPointTypes.SHERE_SCORE);
            }

            @Override
            public void onWxShareFailure(int var, String var1) {
                ToastUtil.INSTANCE.toastCenterError("分享失败");

            }

            @Override
            public boolean onWxShareCancel() {
                ToastUtil.INSTANCE.toastCenter(mContext, "取消分享", R.mipmap.ic_cancel);

                return false;
            }
        });
        ShareMsgObj shareMsgObj = new ShareMsgObj();
        shareMsgObj.setWxType(wxType);//类型：微信朋友1，微信朋友圈2
        shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);
        //        shareMsgObj.setMsgTitle(mTitleText);

        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.lsw_share_icon);
        shareMsgObj.setThunbBmp(bmp);
        String sharePara = null;

        if (null != mLswUploadResult && mExamData != null) {

            sharePara = getString(R.string.str_share_para, EConstants.CLIENT_ID, String.valueOf(getUserInfoBase().getUserId()), String.valueOf(EApplication.BRAND_ID), mExamData.getVersionId(), mLswUploadResult.getDoworkId());
            Log.d(TAG, "########shareUrl#########" + sharePara);
            String strBase64 = Base64Utils.getBase64(sharePara);
            String shareUrl = EpaperConstant.URL_LSW_SHARE + strBase64;
            shareMsgObj.setUrl(shareUrl);

            String shareContent;
            if (mLswScoreResult != null && mLswScoreResult.getStatus() != EpaperConstant.SCORE_STATUS_UNCOMPLETE && mLswScoreResult.getStatus() != EpaperConstant.SCORE_STATUS_TSMK_UNCOMPLETE
                    && mLswScoreResult.getStatus() != EpaperConstant.SCORE_STATUS_ONLINEANSWER_UNCOMPLETE) {
                String score = getString(R.string.speech_word_score, MeUtil.formatScore(mLswScoreResult.getScore()));
                shareContent = getString(R.string.str_share_content, score);
            } else {
                shareContent = getString(R.string.str_share_content2);
            }
            if (wxType == 1) {
                shareMsgObj.setMsgTitle(mTitleText);
                shareMsgObj.setMsgDesription(shareContent);
            } else if (wxType == 2) {
                shareMsgObj.setMsgTitle(shareContent);
                shareMsgObj.setMsgDesription(mTitleText);
            }
            WxShareHelper.getInstance().sendReq(shareMsgObj);

        }

    }

    private void shareAddPointType(String doWorkId, String type) {
        MeDao.getInstance().addPoint(EApplication.getInstance().getUserInfoBase().getUserId() + "", EApplication.getInstance().getUserInfoBase().getRealName(), type, doWorkId + "");
    }

    GoBackListener goBackListener = new GoBackListener() {
        @Override
        public void goBack() {

            if (!isSubmited) {

                showConfirmEndDialog();

            } else {

                sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG));
                sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
                finish();
            }
        }
    };


    private void onUploadStateDeal() {
        if (null != mLswAnswerList && mRetryIndex < mLswAnswerList.size()) {

            LswAnswer lswAnswer = mLswAnswerList.get(mRetryIndex);
            //如果文件丢失当没做，不评分
            if (lswAnswer.getAnswerType() != Questions.AnswerType.QUESTION_TYPE_CHOICE && (lswAnswer.getAnswerType() != Questions.AnswerType.QUESTION_TYPE_FILL_BLANK)) {
                File file = new File(lswAnswer.getAnswerContents().get(0).getContent());
                if (file.exists() && file.length() > 0) {


                    if (EConstants.IS_YOUKE) {
                        //do nothing
                    } else {
                        LswDao.getInstance().submitMakeScore(lswAnswer, isCorrect, new BaseExtCallBack(mContext, String.valueOf(getUserInfoBase().getUserId())) {
                            @Override
                            public void success(Object data) {

                                RecordSubmitPart recordSubmitPart = (RecordSubmitPart) data;
                                mLswAnswerList.get(mRetryIndex).setUploadState(LswAnswer.SUCCESS);
                                mLswAnswerList.get(mRetryIndex).setRecordSubmitPart(recordSubmitPart);
                                Log.d(TAG, "##########重新上传成功#########");
                                retryCallback(true);

                            }

                            @Override
                            public void failed(int errorCode, Object data) {
                                super.failed(errorCode, data);
                                failed(data);
                            }

                            @Override
                            public void failed(Object data) {
                                mLswAnswerList.get(mRetryIndex).setUploadState(LswAnswer.FAIL);

                                if (data != null) {
                                    Log.d(TAG, "##########重新上传失败#########" + data.toString());
                                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, data.toString(), "重新上传失败" + getUrl());
                                }

                                retryCallback(false);
                            }
                        });
                    }

                } else {
                    //文件丢失
                    mLswAnswerList.remove(lswAnswer);
                    mRetryIndex--;
                    retryCallback(false);
                }
            } else {
                retryCallback(false);
            }
        }
    }


    private void retryCallback(boolean isSuccess) {
        mRetryIndex++;
        //          等于  列表遍历完都木有失败
        for (int i = mRetryIndex; i <= mLswAnswerList.size(); i++) {
            mRetryIndex = i;
            if (i < mLswAnswerList.size() && mLswAnswerList.get(i).getUploadState() == LswAnswer.FAIL
                    && (mLswAnswerList.get(i).getAnswerType() != Questions.AnswerType.QUESTION_TYPE_CHOICE)
                    && (mLswAnswerList.get(i).getAnswerType() != Questions.AnswerType.QUESTION_TYPE_FILL_BLANK)) {
                break;
            }
        }

        if (mRetryIndex < mLswAnswerList.size()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //                int progress = mRetryIndex * 100 / (mRetryQuestionList.size() + mRetrySuccessList.size());
                    seek_bar_make_score.setProgress(progress);
                }
            });
            //下一题未上传成功的
            onUploadStateDeal();

        } else {
            isRetryOver = true;
            if (!isHashUploadFail()) {
                if (EConstants.IS_YOUKE) {
                    NewLoginDialog newLoginDialog = new NewLoginDialog(ListenSpeakResultActivity.this);
                    newLoginDialog.showLoginDialog();
                } else {
                    commitHomeWork();
                }
            } else {
                //如果有未成功的，下一轮重试
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        updateStateImg(RESULT_STATE_UPLOAD_FAIL, 0);
                    }
                });
            }
        }
    }

    /**
     * 获取本地作业详情
     */
    private void getLocalMyWorkDetails() {
        SerializableManager.getInstance().deSerialize(

                SerializableManager.SerializeKey.SHARE_KEY_NOTIFICATION_LIST,

                new BaseCallBack() {


                    @Override
                    public void success(Object data) {
                        if (data != null) {
                            mLocalWorkList = (List<MyWork>) data;
                        }
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                    }

                    @Override
                    public void failed(Object data) {
                    }
                });

    }

    private void updateStateImg(int state, float totalScore) {

        switch (state) {
            case RESULT_STATE_UPLOADING:

                img_upload_state.setImageResource(R.mipmap.img_upload_state_ing);

                //score_result_page.setVisibility(View.GONE);
                result_lay.setVisibility(View.GONE);

                handle_state_upload_ing.setVisibility(View.VISIBLE);

                btn_retry_commit.setVisibility(View.GONE);

                break;
            case RESULT_STATE_UPLOAD_SUCCESS:

                img_upload_state.setImageResource(R.mipmap.img_upload_state_success);
                //score_result_page.setVisibility(View.VISIBLE);

                handle_state_upload_ing.setVisibility(View.GONE);
                btn_retry_commit.setVisibility(View.GONE);
                //                tx_work_score.setText("评分中");
                //                img_arrow_shuaxin.setVisibility(View.VISIBLE);

                result_lay.setVisibility(View.VISIBLE);
                if (null != mWorkContents) {
                    nowDate = mWorkContents.getNowDate();
                    // 查看类型：0 提交立马能查看，1截止时间到后查看
                    showScoreMod = mWorkContents.getShowScoreMode();
                }
                score_result_page.setEvaluateState(0, false, "0", lsMode, nowDate, effectiveDate, showScoreMod, serviceExpired);

                try {
                    //作业过来的
                    if (Long.valueOf(mWorkId) > 0) {
                        score_result_page.setRankLinIsVis(View.VISIBLE);

                        score_result_page.setOnToRankListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                MeJumpManager.jumpToRankH5Activity(R.string.go_back, ListenSpeakResultActivity.this, mContentId + "", mWorkContents.getResourceName());
                            }
                        });
                    } else {
                        //自主学习
                        score_result_page.setRankLinIsVis(View.GONE);
                    }

                } catch (Exception e) {
                    score_result_page.setRankLinIsVis(View.GONE);
                    e.printStackTrace();
                }
                break;

            case RESULT_STATE_EVALUATE_SUCCESS:

                img_upload_state.setImageResource(R.mipmap.img_upload_state_success);

                handle_state_upload_ing.setVisibility(View.GONE);
                btn_retry_commit.setVisibility(View.GONE);

                String score = getString(R.string.speech_word_score, MeUtil.formatScore(totalScore));

                result_lay.setVisibility(View.VISIBLE);

                if (null != mWorkContents) {
                    nowDate = mWorkContents.getNowDate();
                    // 查看类型：0 提交立马能查看，1截止时间到后查看
                    showScoreMod = mWorkContents.getShowScoreMode();
                }

                score_result_page.setEvaluateState(0, true, score, lsMode, nowDate, effectiveDate, showScoreMod, serviceExpired);


                try {
                    //作业过来的
                    if (Long.valueOf(mWorkId) > 0) {
                        score_result_page.setRankLinIsVis(View.VISIBLE);

                        score_result_page.setOnToRankListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                MeJumpManager.jumpToRankH5Activity(R.string.go_back, ListenSpeakResultActivity.this, mContentId + "", mWorkContents.getResourceName());
                            }
                        });
                    } else {
                        //自主学习
                        score_result_page.setRankLinIsVis(View.GONE);
                    }

                } catch (Exception e) {
                    score_result_page.setRankLinIsVis(View.GONE);
                    e.printStackTrace();
                }

                break;

            case RESULT_STATE_UPLOAD_FAIL:

                img_upload_state.setImageResource(R.mipmap.img_upload_state_fail);
                //score_result_page.setVisibility(View.GONE);
                result_lay.setVisibility(View.GONE);
                handle_state_upload_ing.setVisibility(View.GONE);
                btn_retry_commit.setVisibility(View.VISIBLE);
                break;
        }

    }


    /**
     * 是否还有文件上传失败
     *
     * @return
     */
    private boolean isHashUploadFail() {
        if (null != mLswAnswerList) {
            for (LswAnswer lswAnswer : mLswAnswerList) {
                if (lswAnswer.getUploadState() == LswAnswer.FAIL && (lswAnswer.getAnswerType() != Questions.AnswerType.QUESTION_TYPE_CHOICE)
                        && (lswAnswer.getAnswerType() != Questions.AnswerType.QUESTION_TYPE_FILL_BLANK)) {
                    return true;
                }
            }
        }

        return false;
    }

    private int getSuccessCount() {
        int failCount = 0;

        for (LswAnswer lswAnswer : mLswAnswerList) {
            if (lswAnswer.getUploadState() == LswAnswer.SUCCESS) {
                failCount++;
            }
        }
        return failCount;
    }


    /**
     * 清除记录
     */
    private void clearRecord() {
        //        清除本次做作业或自主练习活动key,只有活动key 清
        CWSys.setSharedString(ListenSpeakUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, mWorkId, doWorkType), null);
        CWSys.setSharedBoolean(ListenSpeakUtil.getStartDateIsUploadSaveKey(mDownLoadInfo, mModule, position, mWorkId, doWorkType), false);
        //提交成功 清除开始时间
        CWSys.setSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, mWorkId), 0);
    }


    @Override
    protected void loadData() {


    }


    private void commitHomeWork() {
        //作业没有或者自主练习用个人信息的班级
        if (null == mClassId && EApplication.getInstance().getClazz() != null)
            mClassId = String.valueOf(EApplication.getInstance().getClazz().getId());
        String uuid = CWSys.getSharedString(ListenSpeakUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, mWorkId, doWorkType), null);
        Log.d(TAG, "#######提交作业 uuid#########" + uuid);
        if (null == uuid) {
            if (isCorrect) {
                uuid = "isCorrect";
            } else {
                //有可能提交成功清除uuid后再结果页面停留或者用清理软件销毁当前页面，重新生成页面后 uuid 没有
                finish();
            }
        }
        ArrayList<LswAnswer> lswList = new ArrayList<>();
        if (null != mLswAnswerList) {
            for (LswAnswer lswAnswer : mLswAnswerList) {
                if (lswAnswer.getAnswerContents() != null && lswAnswer.getAnswerContents().size() > 0 &&
                        (lswAnswer.getAnswerType() == Questions.AnswerType.QUESTION_TYPE_CHOICE || lswAnswer.getAnswerType() == Questions.AnswerType.QUESTION_TYPE_FILL_BLANK)) {
                    lswList.add(lswAnswer);
                }
            }
        }

        int audioAnswerSize = mLswAnswerList.size() - lswList.size();


        //防止快速交空白卷没有做题时间，后台参数校验不过
        if (totalTime < 1) {
            totalTime = 1;
        }

        if (mServiceId < 1) {
            //防止提交作业提交不了
            mServiceId = 1;
        }
        LswDao.getInstance().submitHomeWork(uuid, mWorkId, mClassId, totalTime, mServiceId, lswList,
                mDownLoadInfo, mModule, position, mContentId, mTotalScore, audioAnswerSize,
                (mWorkContents != null ? mWorkContents.getDoWorkId() : ""), (isCorrect ? 2 : doWorkType), startTime,
                new BaseExtCallBack(mContext, String.valueOf(getUserInfoBase().getUserId())) {

                    @Override
                    public void success(Object data) {
                        super.success(data);
                        //即使客户端上传成功，服务器也可能录音文件丢失，这时候需要重传
                        Log.d(TAG, "#######提交作业成功#########");
                        mLswUploadResult = (LswUploadResult) data;
                        returnWorkLong = mLswUploadResult.getWorkLong();
                        setScore();
                        MeDao.getInstance().getUserPoint();
                        if (null == mLswUploadResult.getReSubmitParts() || mLswUploadResult.getReSubmitParts().size() == 0) {
                            //服务器没有丢失文件,无需重传的录音文件
                            clearRecord();
                            updateStateImg(RESULT_STATE_UPLOAD_SUCCESS, 0);
                            Log.d(TAG, "#######mLswUploadResult.getDoworkId()#########" + mLswUploadResult.getDoworkId());
                            //通知刷新作业列表
                            sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG));
                            sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
                            getScoreResult(mLswUploadResult.getDoworkId());

                            isSubmited = true;

                        } else if (mLswUploadResult.getReSubmitParts() != null && mLswUploadResult.getReSubmitParts().size() > 0) {
                            //找出服务器丢失的重传

                            List<RecordSubmitPart> recordSubmitPartList = mLswUploadResult.getReSubmitParts();

                            for (RecordSubmitPart recordSubmitPart : recordSubmitPartList) {

                                for (int k = 0; k < mLswAnswerList.size(); k++) {
                                    if (mLswAnswerList.get(k).getRecordSubmitPart() != null && mLswAnswerList.get(k).getRecordSubmitPart().getPartId().equals(recordSubmitPart.getPartId())) {
                                        mLswAnswerList.get(k).setUploadState(LswAnswer.FAIL);
                                    }
                                }

                            }

                            startRetry();

                        }

                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        if (errorCode == 105) {
                            clearRecord();
                            setScore();
                        } else {
                            failed(data);
                        }

                    }

                    @Override
                    public void failed(Object data) {
                        String errorMsg = null;
                        if (data != null) {
                            errorMsg = data.toString();
                        }
                        Log.d(TAG, "#######提交作业失败#########" + errorMsg);
                        updateStateImg(RESULT_STATE_UPLOAD_FAIL, 0);
                    }
                });
    }

    private void setScore() {
        //如果返回作业用时失败 则使用旧用时
        if (returnWorkLong != 0) {
            score_result_page.setWorkTime(ListenSpeakUtil.formatWorkLong(this, (int) returnWorkLong));
        } else {
            score_result_page.setWorkTime(ListenSpeakUtil.formatWorkLong(this, totalTime));
        }
    }


    private void getScoreResult(String doworkId) {

        showCricleProgress();
        LswDao.getInstance().getLswScoreResult(doworkId, new BaseCallBack() {

            @Override
            public void success(Object data) {
                super.success(data);

                hideCricleProgress();
                mLswScoreResult = (LswScoreResult) data;
                sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG));
                sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
                if (null != mLswScoreResult) {

                    if (mLswScoreResult.getStatus() == 1 || mLswScoreResult.getStatus() == 4) {
                        updateStateImg(RESULT_STATE_EVALUATE_SUCCESS, mLswScoreResult.getScore());
                    } else if (mLswScoreResult.getStatus() == EpaperConstant.SCORE_STATUS_UNCOMPLETE) {
                        updateStateImg(RESULT_STATE_UPLOAD_SUCCESS, 0);
                    } else if (mLswScoreResult.getStatus() == EpaperConstant.SCORE_STATUS_TSMK_UNCOMPLETE) {
                        score_result_page.goneshuaxin(ishasObj);
                        updateStateImg(RESULT_STATE_UPLOAD_SUCCESS, 0);
                    } else {
                        if (ishasObj) {
                            CWLog.d(TAG, "###########评分中############");
                            score_result_page.goneshuaxin(ishasObj);
                            updateStateImg(RESULT_STATE_UPLOAD_SUCCESS, 0);
                        } else {
                            updateStateImg(RESULT_STATE_UPLOAD_SUCCESS, 0);
                        }

                    }
                }
            }

            @Override
            public void failed(int errorCode, Object data) {

                failed(data);

            }

            @Override
            public void failed(Object data) {
                CWLog.d(TAG, "###########获取评分失败############");

                if (data != null) {
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, data.toString(), "听说模考获取分数失败" + getUrl());
                }

                hideCricleProgress();
            }
        });
    }


    private void showNetSpeed() {

        long nowTotalRxBytes = getTotalRxBytes();
        long nowTimeStamp = System.currentTimeMillis();
        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换

        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;

        Message msg = mHandler.obtainMessage();
        msg.what = MSG_NET_SPEED;
        //        Log.d(TAG, "################String.valueOf(speed)################"+String.valueOf(speed));
        msg.obj = (int) speed;
        mHandler.sendMessage(msg);//更新界面
    }


    private long lastTotalRxBytes = 0;
    private long lastTimeStamp = 0;

    private long getTotalRxBytes() {
        return TrafficStats.getUidRxBytes(getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
    }

    TimerTask netSpeedTask = new TimerTask() {
        @Override
        public void run() {

            if (!isSubmited && !isFinishing()) {
                showNetSpeed();
            } else {
                //提交成功后就不需要展示网络状况
                cancel();
            }

        }
    };


    private long getRemainUploadFileSize() {

        long remainSize = 0;

        for (LswAnswer lswAnswer : mLswAnswerList) {
            if (lswAnswer.getUploadState() == LswAnswer.FAIL) {
                if (null != lswAnswer.getAnswerContents() && lswAnswer.getAnswerContents().size() > 0) {
                    File file = new File(lswAnswer.getAnswerContents().get(0).getContent());
                    if (file.exists()) {
                        remainSize = remainSize + file.length();
                    }
                }
            }
        }

        return remainSize / 1024;
    }


    private TopWarningMsgDialog mTopWarningMsgDialog;

    public void showTopHintDialogWithAnim(Context context, String topHintMsg, int topOffset) {

        mTopWarningMsgDialog = new TopWarningMsgDialog(context, topHintMsg);
        Window dialogWindow = mTopWarningMsgDialog.getWindow();
        dialogWindow.setWindowAnimations(R.style.dialog_window_anim); //设置窗口弹出动画
        dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
        WindowManager.LayoutParams params = mTopWarningMsgDialog.getWindow().getAttributes();

        if (topOffset > 0) {
            params.y = DisplayUtils.dip2px(context, topOffset);
        } else {
            //45 是标题栏高度，在标题栏下面
            params.y = DisplayUtils.dip2px(context, 45);
        }
        params.x = 0;
        dialogWindow.setAttributes(params);
        mTopWarningMsgDialog.setCanceledOnTouchOutside(true); //点击dialog区域之外的地方，dialog消失
        mTopWarningMsgDialog.show();
    }


    private boolean isOnlyChoiceOrBlank() {
        boolean chOrBlank = true;

        for (LswAnswer lswAnswer : mLswAnswerList) {
            if (lswAnswer.getAnswerType() != Questions.AnswerType.QUESTION_TYPE_CHOICE && lswAnswer.getAnswerType() != Questions.AnswerType.QUESTION_TYPE_FILL_BLANK) {
                return false;
            }
        }

        return chOrBlank;
    }


    public void isSupportQQAndQQZone() {
        if (EConstants.QQ_APP_ID.equals("") || null == EConstants.QQ_APP_ID) {
            qq.setImageResource(R.mipmap.share_qq_unstalled);
            qqFriend.setImageResource(R.mipmap.share_qq_space_unstalled);
            qq.setEnabled(false);
            qqFriend.setEnabled(false);
        }
    }


    /**
     * 获取听说模块试卷数据
     */
    public void getExamData() {

        showMiddleProgressBar(getTitleText());

        //        String path = ESystem.getPackagesJsonPath(mModule.getResourceList().get(position).getResourceFile());
        String path;
        String tag = "";
        if (doWorkType == 1) {
            tag = "订正错题  ";
        }
        if (mDownLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
            path = ESystem.getPackagesJsonPathNew(mDownLoadInfo.getBookId(), mDownLoadInfo.getChapterId(), mDownLoadInfo.getModuleId(), mDownLoadInfo.getVersionId());
            score_result_page.setTitleText(tag + mDownLoadInfo.getResourceName());
            mTitleText = mDownLoadInfo.getResourceName();

        } else {
            path = ESystem.getPackagesJsonPath(mModule.getResourceList().get(position).getResourceFile());
            score_result_page.setTitleText(tag + mModule.getResourceList().get(position).getResourceName());
            mTitleText = mModule.getResourceList().get(position).getResourceName();
        }

        //获取作业资源
        EpaperDao.getInstance().getSerializableObjects(path,
                ListenspeakExam.class, new BaseExtCallBack(ListenSpeakResultActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                    @Override
                    public void success(final Object data) {
                        super.success(data);
                        mExamData = (ListenspeakExam) data;
                        List<String> errorResourceList = new ArrayList<>();
                        if (doWorkType == 1) {
                            if (mWorkContents != null && !TextUtils.isEmpty(mWorkContents.getErrorResource())) {
                                // 有错题
                                String[] errorResource = mWorkContents.getErrorResource().split(",");
                                errorResourceList = Arrays.asList(errorResource);
                            }
                        }
                        /**
                         * 选中的资源(同步跟读：id字符串；听说模考：下标字符串)//选择布置的
                         * 目前只有听说模考有字段内容，比如一份试卷有10题只选中其中几题布置
                         */
                        if (!TextUtils.isEmpty(checkedResource)) {
                            // 有选题
                            String[] checkedQuesIndexs = checkedResource.split(",");
                            List<ResourceDetail> items = new ArrayList<ResourceDetail>();
                            for (String quesIndex : checkedQuesIndexs) {
                                int bigQuesIndex = Integer.parseInt(quesIndex);
                                ResourceDetail mResourceDetail = mExamData.getItems().get(bigQuesIndex);
                                if (doWorkType == 1 && errorResourceList.size() > 0) {
                                    List<Questions> errorQuestions = new ArrayList<>();
                                    for (Questions mQuestionItem : mResourceDetail.getQuestions()) {
                                        int minQuest = mQuestionItem.getChildren().size();
                                        if (minQuest == 0) {
                                            //没有子题目
                                            String versionId = mQuestionItem.getVersionId();
                                            if (errorResourceList.contains(versionId)) {
                                                errorQuestions.add(mQuestionItem);
                                            }
                                        } else {
                                            //有子题目
                                            List<Questions> children = mQuestionItem.getChildren();
                                            List<Questions> errorChildren = new ArrayList<>();
                                            for (Questions mCQuestionItem : children) {
                                                String versionId = mCQuestionItem.getVersionId();
                                                if (errorResourceList.contains(versionId)) {
                                                    errorChildren.add(mCQuestionItem);
                                                }
                                            }
                                            if (errorChildren.size() > 0) {
                                                mQuestionItem.setChildren(errorChildren);
                                                errorQuestions.add(mQuestionItem);
                                            }
                                        }
                                    }
                                    if (errorQuestions.size() > 0) {
                                        mResourceDetail.setQuestions(errorQuestions);
                                        items.add(mResourceDetail);
                                    }
                                } else {
                                    items.add(mResourceDetail);
                                }
                            }
                            mExamData.setItems(items);
                        } else {
                            if (doWorkType == 1 && errorResourceList.size() > 0) {
                                List<ResourceDetail> items = new ArrayList<ResourceDetail>();
                                for (ResourceDetail mResourceDetail : mExamData.getItems()) {
                                    List<Questions> errorQuestions = new ArrayList<>();
                                    for (Questions mQuestionItem : mResourceDetail.getQuestions()) {
                                        int minQuest = mQuestionItem.getChildren().size();
                                        if (minQuest == 0) {
                                            //没有子题目
                                            String versionId = mQuestionItem.getVersionId();
                                            if (errorResourceList.contains(versionId)) {
                                                errorQuestions.add(mQuestionItem);
                                            }
                                        } else {
                                            //有子题目
                                            List<Questions> children = mQuestionItem.getChildren();
                                            List<Questions> errorChildren = new ArrayList<>();
                                            for (Questions mCQuestionItem : children) {
                                                String versionId = mCQuestionItem.getVersionId();
                                                if (errorResourceList.contains(versionId)) {
                                                    errorChildren.add(mCQuestionItem);
                                                }
                                            }
                                            if (errorChildren.size() > 0) {
                                                mQuestionItem.setChildren(errorChildren);
                                                errorQuestions.add(mQuestionItem);
                                            }
                                        }
                                    }
                                    if (errorQuestions.size() > 0) {
                                        mResourceDetail.setQuestions(errorQuestions);
                                        items.add(mResourceDetail);
                                    }
                                }
                                mExamData.setItems(items);
                            }
                        }

                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        failed(data);
                    }

                    @Override
                    public void failed(Object data) {

                    }
                }

        );
    }


    @Override
    public void finish() {
        if (null != mLswScoreResult) {
            //为解决

            Intent intent = new Intent(EpaperConstant.INTENT_BOACK_REF_WORK);
            //        作业状态(1:已提交 2:退回 4:已批改完成 8:无法识别答题卡 16:等待批改)
            int workStatus = 1;//听说模考评分中传16，其他默认传1.
            intent.putExtra(IntentFlag.INTENT_FLAG_WORK_STATUS, mLswScoreResult.getStatus());//
            intent.putExtra(IntentFlag.INTENT_FLAG_ACTUAL_SCORE, mLswScoreResult.getScore());
            sendBroadcast(intent);
        }

        super.finish();
    }

}
